package com.dbq.fast.business.me;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.business.main.dialog.TipDialog;
import com.dbq.fast.business.main.dialog.base.TipBaseDialog;
import com.dbq.fast.business.me.bean.FeedbackBean;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.HttpResult;
import com.dbq.fast.common.net.LogHttpManager;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SystemUtil;
import com.yiba.logutils.LogUtils;
import com.yiba.logutils.utils.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.dbq.fast.business.main.dialog.TipDialog.UPLOAD_LOG_FEEDBACK;

public class FeedbackActivity extends BaseActivity {
    @BindView(R.id.right_submit)
    TextView rightSubmit;

    @BindView(R.id.btn_submit)
    Button btnSubmit;

    @BindView(R.id.content)
    EditText etContent;

    @BindView(R.id.tv_content_length)
    TextView tvContentLength;

    @BindView(R.id.link_contact)
    EditText etContact;
    @BindView(R.id.back)
    ImageView backIv;

    private List<File> files; //上传的日志文件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        ButterKnife.bind(this);
        initListener();
    }

    private void initListener() {
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvContentLength.setText((s == null ? 0 : s.length()) + "/200");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        View.OnClickListener listener = new CommonListener();
        rightSubmit.setOnClickListener(listener);
        btnSubmit.setOnClickListener(listener);
        backIv.setOnClickListener(v -> onBackPressed());
    }

    private class CommonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            submit();
        }
    }

    private void submit() {
        final File logFolder = new File(LogUtils.getInstance().getROOT());
        // 如果Log文件夹都不存在，说明不存在崩溃日志，检查缓存是否超出大小后退出
        String content = etContent.getText().toString().trim();
        String contact = etContact.getText().toString().trim();
        boolean haveFile = (logFolder.exists() && logFolder.listFiles().length != 0);
        if (content.isEmpty()) {
            Toast.makeText(App.getContext(), R.string.please_write_feedback_info, Toast.LENGTH_SHORT).show();
            return;
        }
        if (isResume) {
            ProgressDialogUtil.showProgress(FeedbackActivity.this, "", "");
        }
        if (haveFile || !content.isEmpty()) {
            List<MultipartBody.Part> result;
            FeedbackBean feedbackBean = new FeedbackBean();
            feedbackBean.uId = User.getInstance().getAccount();
            feedbackBean.contact = contact;
            feedbackBean.content = content;
            if (haveFile) {
                files =replaceUid(FileUtil.getLogInfoList(logFolder));
                if (files != null) {
                    result = filesToMultipartBody(files);
                    uploadFileAndFeedback(result, feedbackBean);
                } else {
                    uploadFeedback(feedbackBean);
                }
            } else {
                uploadFeedback(feedbackBean);
            }

        } else {
            if (isResume) {
                ProgressDialogUtil.hideProgress();
            }
            if (content.isEmpty()) {
                Toast.makeText(this, R.string.please_write_feedback_info, Toast.LENGTH_SHORT).show();
                return;
            }
            if (isResume) {
                TipDialog.newInstance(UPLOAD_LOG_FEEDBACK).show(getSupportFragmentManager());
            }
        }
    }

    private void uploadFileAndFeedback(List<MultipartBody.Part> result, FeedbackBean feedbackBean) {
//        Map<String, String> param = new HashMap<>();
//        param.put("uId", feedbackBean.uId);
//        param.put("problem", feedbackBean.content);
//        param.put("contactInfo", feedbackBean.contact);
//        param.put("vpnId", User.getInstance().getVpnId());
//        param.put("appName", "unicorn");
        LogHttpManager.getInstance().getHttpService()
                .logUpload(result, feedbackBean.uId, feedbackBean.content, feedbackBean.contact, User.getInstance().getVpnId(), "unicorn", SystemUtil.getAppVersionName(App.getContext()))
                .retry(2)
                .compose(new CommonTransformer<>())
                .subscribe(new OkConsumer(), new ErrorConsumer());
    }

    private void uploadFeedback(FeedbackBean feedbackBean) {
        LogHttpManager.getInstance()
                .getHttpService()
                .logUpload(feedbackBean.uId, feedbackBean.content, feedbackBean.contact, User.getInstance().getVpnId(), "unicorn", SystemUtil.getAppVersionName(App.getContext()))
                .retry(2)
                .compose(new CommonTransformer<>())
                .subscribe(new OkConsumer(), new ErrorConsumer());
    }

    private class OkConsumer implements Consumer<HttpResult> {

        @Override
        public void accept(HttpResult httpResult) throws Exception {
            if (isResume) {
                ProgressDialogUtil.hideProgress();
            }
            //上传成功后需要删除本地日志文件
            try {
                if (files != null && files.size() > 0) {
                    for (File file : files) {
                        file.delete();
                    }
                }
            }catch (Exception e){
                LogUtils.getInstance().log("上传日志成功，本地文件删除失败","上传日志成功，本地文件删除失败"+e.getMessage());
            }

            TipBaseDialog tipBaseDialog = TipDialog.newInstance(UPLOAD_LOG_FEEDBACK);
            tipBaseDialog.setOnClickListener(new TipBaseDialog.IOnClickListener() {

                @Override
                public void operate1Click() {
                    FeedbackActivity.this.finish();
                }

                @Override
                public void operate2Click() {

                }
            });
            tipBaseDialog.show(getSupportFragmentManager());
        }
    }

    private class ErrorConsumer implements Consumer<Throwable> {

        @Override
        public void accept(Throwable throwable) throws Exception {
            if (isResume) {
                ProgressDialogUtil.hideProgress();
            }
            Log.i("throwable", "throwable=" + throwable.toString());
            Toast.makeText(FeedbackActivity.this, R.string.log_feedback_failed, Toast.LENGTH_SHORT).show();
        }
    }

    private List<File> replaceUid(List<File> files) {
        ArrayList<File> result = new ArrayList<>();
        if (files == null) return result;
        try {
            for (File file : files) {
                File res = new File(file.getParent() + "/" + file.getName()+ "_up_" + User.getInstance().getAccount());
                file.renameTo(res);
                result.add(res);
            }
        } catch (IndexOutOfBoundsException ioobe) {
            return null;
        }

        return result;
    }

    private List<MultipartBody.Part> filesToMultipartBody(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());

        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("text/*"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("log", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }

    @Override
    protected void onDestroy() {
        ProgressDialogUtil.hideProgress();
        super.onDestroy();
    }
}
